package com.ccl.keyassistant;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ccl.keyassistant.activity.AddKeyActivity;
import com.ccl.keyassistant.activity.SendKeyActivity;
import com.ccl.keyassistant.commons_codec.digest.DigestUtils;
import com.ccl.keyassistant.fragment.AboutFragment;
import com.ccl.keyassistant.fragment.KeyFragment;
import com.ccl.keyassistant.fragment.LocalFragment;
import com.ccl.keyassistant.utils.L;
import com.ccl.keyassistant.utils.PermissionUtil;
import com.ccl.keyassistant.utils.StaticClass;
import com.ccl.keyassistant.view.CustomDialog;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;


public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener,
        View.OnClickListener, SearchView.OnQueryTextListener, SearchView.OnCloseListener {

    private TextView mTextMessage;
    private ViewPager mViewPager;
    private ArrayList<Fragment> mFragmentList;
    private BottomNavigationView navigation;
    private FloatingActionMenu mFabMenu;
    //上面的那个button
    private FloatingActionButton mFirstFabBtn;
    //下面的button
    private FloatingActionButton mSecondFabBtn;

    //记录当前处于的fragment
    private int mCurrentFragment;

    //初始化按钮旁的提示语数组
    private String[] menuTitle = new String[]{
            "删除当前远程连接", "添加一个远程连接",
            "手动添加密钥", "扫描二维码获取"
    };


    //所需要的权限
    private static String[] permissions = new String[]{
            Manifest.permission.CAMERA,Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };

    //保存为获得的权限
    private static List<String> deniedPermission = new ArrayList<String>();
    private TextView mAppName;
    private SearchView mSearch;
    private Toolbar mToolBar;
    private OnSearchCommittedListener onSearchCommittedListener;
    private LocalFragment localFragment;
    private KeyFragment keyFragment;
    private AboutFragment aboutFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化Fragment
        initViews();

        initPermission();

        mTextMessage = (TextView) findViewById(R.id.message);
        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //开启事务
//                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
//                android.R.id.content //代表当前手机的窗体
                switch (item.getItemId()) {
                    case R.id.navigation_PC:
                        mViewPager.setCurrentItem(0);
                        return true;
                    case R.id.navigation_KEY:
                        mViewPager.setCurrentItem(1);
                        return true;
                    case R.id.navigation_ABOUT:
                        mViewPager.setCurrentItem(2);
                        return true;
                }
                return false;
            }
        });


    }


    private void initViews() {

        //初始化ToolBar
        View tb = findViewById(R.id.tb_main);
        mToolBar = (Toolbar) tb.findViewById(R.id.toolbar);
        mAppName = (TextView) tb.findViewById(R.id.tv_appName);
        mSearch = (SearchView) tb.findViewById(R.id.sv_search);
        mSearch.setQueryHint("请输入搜索内容");
        //设置搜索框有字时显示叉叉，无字时隐藏叉叉
//        mSearch.onActionViewExpanded();
        mSearch.setIconified(false);
        //默认不显示
        mSearch.setVisibility(View.GONE);
        //设置searchview的监听事件,字符改变以及关闭事件
        mSearch.setOnQueryTextListener(this);
        mSearch.setOnCloseListener(this);
        setSupportActionBar(mToolBar);
        //去掉默认显示的title
        getSupportActionBar().setDisplayShowTitleEnabled(false);


        mFragmentList = new ArrayList<>();
        localFragment = new LocalFragment();
        keyFragment = new KeyFragment();
        aboutFragment = new AboutFragment();
        mFragmentList.add(localFragment);
        mFragmentList.add(keyFragment);
        mFragmentList.add(aboutFragment);

        //初始化 悬浮菜单
        mFabMenu = (FloatingActionMenu) findViewById(R.id.fabmenu);
        //默认不显示
        mFabMenu.setVisibility(View.GONE);
        mFirstFabBtn = (FloatingActionButton) findViewById(R.id.first_menu_item);
        mSecondFabBtn = (FloatingActionButton) findViewById(R.id.second_menu_item);

        //设置第一和第二个按键的点击事件
        mFirstFabBtn.setOnClickListener(this);
        mSecondFabBtn.setOnClickListener(this);
        mFabMenu.setClosedOnTouchOutside(true);

        mViewPager = (ViewPager) findViewById(R.id.mViewPager);
        //设置ViewPager数据适配器，将Fragment绑定到ViewPager上
        mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return mFragmentList.size();
            }
        });

        mViewPager.addOnPageChangeListener(this);

    }

    @Override
    public void onPageSelected(int position) {
        //该方法只在滑动停止时调用，position滑动停止所在页面位置
        //                当滑动到某一位置，导航栏对应位置被按下
        navigation.getMenu().getItem(position).setChecked(true);
        //根据当前所在的Fragment，设置相应的提示信息
        //当滑动到第三个Fragment时，隐藏悬浮按钮
        switch (position) {
//            第一个Fragment
            case StaticClass.FIRST_FRAGMENT:
                mCurrentFragment = StaticClass.FIRST_FRAGMENT;
                mFabMenu.setVisibility(View.GONE);
                //隐藏状态栏
                mSearch.setVisibility(View.GONE);
                mAppName.setVisibility(View.VISIBLE);
                break;
            //第二个Fragment
            case StaticClass.SECOND_FRAGMENT:
                mCurrentFragment = StaticClass.SECOND_FRAGMENT;
                mFabMenu.setVisibility(View.VISIBLE);
                mFirstFabBtn.setLabelText(menuTitle[3]);
                mFirstFabBtn.setImageResource(R.drawable.fab_scan);
                mSecondFabBtn.setLabelText(menuTitle[2]);
                //更新数据
                keyFragment.search("");
                //显示搜索框，隐藏标题
                mSearch.setVisibility(View.VISIBLE);
                mAppName.setVisibility(View.GONE);
                break;
            //第三个Fragment
            case StaticClass.THIRD_FRAGMENT:
                mCurrentFragment = StaticClass.THIRD_FRAGMENT;
                mFabMenu.setVisibility(View.GONE);
                //隐藏搜索框
                mSearch.setVisibility(View.GONE);
                mAppName.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
        //切换fragment时，如果菜单是展开状态，则关闭菜单
        mFabMenu.close(true);
    }

    //依据当前所处的fragment，实现不同的按键点击事件

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.first_menu_item:
                //第一个Fragment
                if (mCurrentFragment == StaticClass.FIRST_FRAGMENT) {
                    //删除当前远程连接
                }
                //第二个Fragment，不会再第三个Fragment
                else {
                    //检查相机权限
                    boolean permitted = PermissionUtil.isPermitted(this,
                            Manifest.permission.CAMERA);
                    if (!permitted) {
                        //申请权限
                        PermissionUtil.requestPermission(MainActivity.this, new String[]{
                                Manifest.permission.CAMERA}, StaticClass.PERMISSION_CAMERA);
                    } else {
                        //扫描二维码
                        scanQRCode();
                    }


                }
                break;
            case R.id.second_menu_item:

                if (mCurrentFragment == StaticClass.FIRST_FRAGMENT) {
//                    Intent intent = new Intent(MainActivity.this, SendKeyActivity.class);
//                    startActivity(intent);
                } else {
                    //手动添加密钥
                    Intent intent = new Intent(MainActivity.this, AddKeyActivity.class);
                    startActivity(intent);
                }
                break;

            default:
                break;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //判断二维码回传的扫描结果,成功
            case StaticClass.OR_REQUEST:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        //获取的数据以字符串形式存在 进行数据的相关操作
                        String qrCodeInfo = data.getStringExtra(Constant.CODED_CONTENT);
                        //进行base64转码
                        Base64.Decoder decoder = Base64.getDecoder();
                        byte[] decode = decoder.decode(qrCodeInfo);
                        try {
                            qrCodeInfo = new String(decode, "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        L.i(qrCodeInfo);
                        //跳转到sendkey activity
                        Intent intent = new Intent(MainActivity.this, SendKeyActivity.class);
                        intent.putExtra("qrCodeInfo", qrCodeInfo);
                        startActivity(intent);

                    }
                } else {
                    Toast.makeText(this, "二维码扫描失败，请重试", Toast.LENGTH_SHORT).show();
                }
                break;
            //判断蓝牙是否开启成功
//            case StaticClass.BLUE_REQUEST_CODE:
//                if (resultCode == RESULT_OK) {
//                    //蓝牙开启成功，查询已经配对的设备
//                } else {
//                    L.d( requestCode + "");
//                    Toast.makeText(this, "蓝牙开启失败，请重试", Toast.LENGTH_SHORT).show();
//                }
//                break;
            default:
                break;
        }

    }


    /**
     * 申请所需要的基础权限
     */
    private void initPermission() {
        for (int i = 0; i < permissions.length; i++) {
            boolean permitted = PermissionUtil.isPermitted(this, permissions[i]);
            //权限未申请成功，添加到未申请权限
            if (!permitted) {
                deniedPermission.add(permissions[i]);
            }
        }
        //申请权限
        PermissionUtil.requestPermission(MainActivity.this, deniedPermission, StaticClass.PERMISSION_ALL);
    }


    /**
     * 权限处理回调函数
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            //所有权限
            case StaticClass.PERMISSION_ALL: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功获取权限
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    deniedPermission.clear();
                } else {
                    //未获取权限
                    Toast.makeText(this, "权限获取失败", Toast.LENGTH_SHORT).show();
                }
                return;
            }
            //位置权限
            case StaticClass.PERMISSION_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功获取权限
                    deniedPermission.remove(Manifest.permission.ACCESS_COARSE_LOCATION);
                    deniedPermission.remove(Manifest.permission.ACCESS_FINE_LOCATION);
                    Toast.makeText(this, "位置权限获取成功", Toast.LENGTH_SHORT).show();
                } else {
                    //未获取权限
                    Toast.makeText(this, "位置权限获取失败", Toast.LENGTH_SHORT).show();
                }
                return;
            }
            //手机权限
            case StaticClass.PERMISSION_PHONE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功获取权限
                    deniedPermission.remove(Manifest.permission.READ_PHONE_STATE);
                    Toast.makeText(this, "手机权限获取成功", Toast.LENGTH_SHORT).show();
                } else {
                    //未获取权限
                    PermissionUtil.requestPermission(MainActivity.this,
                            new String[]{Manifest.permission.READ_PHONE_STATE}, StaticClass.PERMISSION_ALL);
                }
                return;
            }
            //读写权限
            case StaticClass.PERMISSION_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功获取权限
                    Toast.makeText(this, "读写权限获取成功", Toast.LENGTH_SHORT).show();
                    deniedPermission.remove(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    deniedPermission.remove(Manifest.permission.READ_EXTERNAL_STORAGE);
                } else {
                    //未获取权限
                    Toast.makeText(this, "读写权限获取失败", Toast.LENGTH_SHORT).show();
                }
                return;
            }
            //相机权限
            case StaticClass.PERMISSION_CAMERA: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功获取权限
                    Toast.makeText(this, "相机权限获取成功", Toast.LENGTH_SHORT).show();
                    deniedPermission.remove(Manifest.permission.CAMERA);
                    //扫描二维码
                    scanQRCode();

                } else {
                    //未获取权限
                    final CustomDialog dialog = new CustomDialog(this, R.layout.custom_dialog_ok);
                    dialog.show();

                    //利用inflate方式获取控件的点击事件是不生效的
//                    View view = View.inflate(this, R.layout.custom_dialog_ok, null);
                    //利用此方法可以
                    dialog.getWindow().findViewById(R.id.custom_dialog_ok).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            L.i("click");
                            dialog.dismiss();
                            PermissionUtil.requestPermission(MainActivity.this,
                                    new String[]{Manifest.permission.CAMERA}, StaticClass.PERMISSION_CAMERA);
                        }
                    });
                }
                return;
            }
            default:
                break;
        }
    }



    /**
     * 扫描二维码
     */
    private void scanQRCode() {
        //扫描二维码,获取文件信息
        Intent intent = new Intent(this, CaptureActivity.class);
        ZxingConfig config = new ZxingConfig();
        config.setPlayBeep(true);//是否播放提示音
        config.setFullScreenScan(false);//是否全屏扫描
        config.setShake(true);//扫描结束后是否震动
        config.setScanLineColor(R.color.scanLineColor);//设置扫描线的颜色
        config.setReactColor(R.color.reactColor);//设置扫描框的四个角上的矩形的颜色
//                    config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
        config.setDecodeBarCode(true);//是否扫描条形码 默认为true
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, StaticClass.OR_REQUEST);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //注意这个方法滑动时会调用多次，下面是参数解释：
        //position当前所处页面索引,滑动调用的最后一次绝对是滑动停止所在页面
        //positionOffset:表示从位置的页面偏移的[0,1]的值。
        //positionOffsetPixels:以像素为单位的值，表示与位置的偏移
    }

    @Override
    public void onPageScrollStateChanged(int state) {
//这个方法在滑动是调用三次，分别对应下面三种状态
// 这个方法对于发现用户何时开始拖动，
// 何时寻呼机自动调整到当前页面，或何时完全停止/空闲非常有用。
//                state表示新的滑动状态，有三个值：
//                SCROLL_STATE_IDLE：开始滑动（空闲状态->滑动），实际值为0
//                SCROLL_STATE_DRAGGING：正在被拖动，实际值为1
//                SCROLL_STATE_SETTLING：拖动结束,实际值为2
    }

    /**
     * serachview的字符查询事件，当点击提交时触发
     *
     * @param query
     * @return
     */
    @Override
    public boolean onQueryTextSubmit(String query) {
        L.i(query);

        //查询数据并显示
        if (onSearchCommittedListener != null) {
            onSearchCommittedListener.searchCommitted(query);
        }
        return false;
    }

    /**
     * 当seerchview的输入框中的字符发送改变时触发
     *
     * @param newText
     * @return
     */
    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }

    /**
     * searchview close调用
     *
     * @return
     */
    @Override
    public boolean onClose() {
        if (onSearchCommittedListener != null) {
            onSearchCommittedListener.searchClose(null);
        }
        return false;
    }


    public interface OnSearchCommittedListener {
        void searchCommitted(String str);

        void searchClose(String str);
    }

    public void SetOnSearchCommittedListener(OnSearchCommittedListener onSearchCommittedListener) {
        this.onSearchCommittedListener = onSearchCommittedListener;
    }

}
